#pragma once
#include "hy_stddef.h"

NS_HY_BEGIN

class HY_DLL  hy_stream 
{
protected:
	schar				*m_buf;

	uint64				m_cur_pos;
	uint64				m_max_pos;
	bool				m_reverse_bytes;
	bool				m_iswchar;
	bool				m_is_write_check_max;
	sint				m_error_pos;
public:
	hy_stream():m_buf( NULL ),m_cur_pos( 0 ), m_max_pos( 0 ),m_reverse_bytes( false ), m_iswchar( false ),
		m_is_write_check_max( true ), m_error_pos( -1 ){};
	virtual ~hy_stream(){};

	static uint16 reverse_endian_uint16( uint16 w )
	{
		return ((w&0xff00)>>8)|((w&0xff)<<8);
	}

	static sint reverse_endian_sint( sint i)
	{
		return (sint)(
			((i&0xff000000)>>24)|
			((i&0x00ff0000)>>8)|
			((i&0x0000ff00)<<8)|
			((i&0xff)<<24));
	}

	static uint64 reverse_endian_uint64(uint64 d)
	{
		return (uint64)(
			((d&0xff000000)>>24)|
			((d&0x00ff0000)>>8)|
			((d&0x0000ff00)<<8)|
			((d&0xff)<<24));
	}

	static float32 reverse_endian_float32(float32 f)
	{
		uint64 d = *(uint64 *)&f;
		uint64 d2 =
			((d&0xff000000)>>24)|
			((d&0x00ff0000)>>8)|
			((d&0x0000ff00)<<8)|
			((d&0xff)<<24);

		return *(float32 *)&d2;
	}

	void				set_cur_pos( uint32 cp ){ m_cur_pos = cp;}
	uint32				get_cur_pos() const { return m_cur_pos; }

	void				set_error_pos( sint pos ){m_error_pos = pos; }
	sint				get_error_pos(){ return m_error_pos; }
	
	const schar*		get_buffer() const { return m_buf; }
	schar*				get_buffer() { return m_buf; }	
	std::string			get_buffer_by_pos( int first_, int end_ );
	void				set_buffer( const char* c, int len );
	void				release_buffer();

	void				set_iswchar( bool iswchar ){ m_iswchar = iswchar; }
	void				set_buffers( void *data ){m_buf = (schar *)data; }
	void				set_max_pos( uint pos ){ m_max_pos = pos; }
	void				set_buffers( void *data, uint size ){ m_buf = (schar *)data; m_max_pos = size; }
	
	// read
	virtual schar				read_schar();
	virtual uchar				read_uchar();
	virtual uint16				read_uint16();
	virtual sint16				read_sint16();
	virtual uint32				read_uint32();
	virtual sint				read_sint();
	virtual float32				read_float32();
	virtual uint64				read_uint64();
	virtual uint16				read_string( schar *buf, uint len );
	virtual uint16				read_string( std::string &buf );

	virtual bool				check_max_pos();
	virtual bool				write_schar( schar c );
	virtual bool				write_uchar( uchar c );
	virtual bool				write_uint16( uint16 c );
	virtual bool				write_sint16( sint16 c );
	virtual bool				write_uint32( uint32 c );
	virtual bool				write_sint( sint c );
	virtual bool				write_float32( float32 c );
	virtual bool				write_uint64( uint64 c );
	virtual bool				write_string( const char *c );
};
NS_HY_END